<script lang="ts">
  import { onMount } from "svelte";
  import * as echarts from "echarts";

  let chartDom: HTMLDivElement;
  let myChart: echarts.ECharts;
  export let dpFictitiousStatisticsData: Record<string, any>[] = [];

  // 基准分辨率
  const baseHeight = 1080;
  let scale = 1;

  // 标记是否需要更新数据
  let needsDataUpdate = false;

  // 计算缩放比例
  const calculateScale = () => {
    const currentHeight = window.innerHeight;
    if (currentHeight < baseHeight) {
      scale = currentHeight / baseHeight;
    } else {
      scale = 1;
    }
    return scale;
  };

  // 生成从今天开始到之前7天的日期
  const getLast7Days = () => {
    const dates = [];
    const today = new Date();
    const options = { month: '2-digit', day: '2-digit', weekday: 'short' };
    for (let i = 0; i < 7; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() - i);
      const formattedDate = date.toLocaleDateString('zh-CN', options);
      dates.push(formattedDate);
    }
    return dates.reverse();
  };

  // 创建图表配置
  const createOption = () => {
    // 计算当前缩放比例
    calculateScale();
    
    return {
      textStyle: {
        fontSize: Math.max(10, Math.round(14 * scale)),
        fontWeight: 'bold',
      },
      grid: {
        top: Math.max(30, Math.round(50 * scale)),
        bottom: 0,
        left: 0,
        right: 0,
        containLabel: true
      },
      xAxis: {
        type: "category",
        data: getLast7Days(),
        axisLabel: {
          formatter: function(value: string) {
            const datePattern = /(\d{2}\/\d{2})(周.)/;
            const matches = value.match(datePattern);
            if (matches && matches.length > 2) {
              return matches[1] + '\n' + matches[2];
            }
            return value;
          },
          fontSize: Math.max(8, Math.round(12 * scale)),
          interval: 1
        },
      },
      yAxis: {
        type: "value",
        splitNumber: 3,
        axisLabel: {
          fontSize: Math.max(8, Math.round(12 * scale)),
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: [
              'transparent',
              'rgba(255, 255, 255, 0.1)',
              'rgba(255, 255, 255, 0.1)',
              'rgba(255, 255, 255, 0.1)',
              'rgba(255, 255, 255, 0.1)'
            ]
          }
        }
      },
      legend: {
        data: ['成功订单金额', '成功订单收益'],
        top: 0,
        textStyle: {
          color: 'rgba(255, 255, 255, 0.7)',
          fontSize: Math.max(8, Math.round(12 * scale))
        }
      },
      series: [
        {
          name: '成功订单金额',
          data: [2, 3, 1, 4, 2, 8, 1],
          type: "line",
          smooth: true,
          symbol: 'circle',
          symbolSize: Math.max(4, Math.round(8 * scale)),
          itemStyle: {
            color: "#18D3EC"
          },
          lineStyle: {
            width: Math.max(1, Math.round(3 * scale)),
            color: "#18D3EC"
          },
          label: {
            show: true,
            position: "top",
            color: "rgba(255,255,255,0.6)",
            fontSize: Math.max(8, Math.round(12 * scale)),
          },
        },
        {
          name: '成功订单收益',
          data: [5, 2, 6, 3, 7, 4, 6],
          type: "line",
          smooth: true,
          symbol: 'circle',
          symbolSize: Math.max(4, Math.round(8 * scale)),
          itemStyle: {
            color: "#FF7A45"
          },
          lineStyle: {
            width: Math.max(1, Math.round(3 * scale)),
            color: "#FF7A45"
          },
          label: {
            show: true,
            position: "top",
            color: "rgba(255,255,255,0.6)",
            fontSize: Math.max(8, Math.round(12 * scale)),
          },
          showSymbol: true,
          effect: {
            show: true,
            period: 3,
            trailLength: 0,
            symbolSize: Math.max(4, Math.round(8 * scale)),
            symbol: 'circle',
            loop: true,
            color: '#FF7A45'
          }
        }
      ],
    };
  };

  // 更新图表数据的函数
  const updateChartData = () => {
    if (myChart && dpFictitiousStatisticsData.length > 0) {
      const option = createOption();
      option.series[0].data = dpFictitiousStatisticsData.map(item => item.orderAmount || 0);
      option.series[1].data = dpFictitiousStatisticsData.map(item => item.incomeAmount || 0);
      myChart.setOption(option);
      console.log('图表数据已更新');
    }
  };

  onMount(() => {
    myChart = echarts.init(chartDom);
    myChart.setOption(createOption());

    // 窗口大小变化处理
    const resizeHandler = () => {
      if (myChart) {
        // 先调整图表大小
        myChart.resize();
        
        // 然后重新应用数据
        updateChartData();
        
        console.log('窗口大小变化，图表已调整并更新数据');
      }
    };
    
    // 使用防抖函数避免频繁触发
    const debounce = (fn, delay) => {
      let timer = null;
      return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(context, args);
        }, delay);
      };
    };
    
    // 创建防抖版本的resize处理函数
    const debouncedResize = debounce(resizeHandler, 200);
    
    window.addEventListener("resize", debouncedResize);

    return () => {
      window.removeEventListener("resize", debouncedResize);
      if (myChart) {
        myChart.dispose();
      }
    };
  });

  // 响应式声明，监听数据变化
  $: if (myChart && dpFictitiousStatisticsData.length > 0) {
    updateChartData();
  }
</script>

<div class="w-full h-full" bind:this={chartDom}></div>